package com.jw.qme.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jw.qme.domain.po.MediaFile;
import com.jw.qme.mapper.MediaFileMapper;
import com.jw.qme.service.MediaFileService;
import com.jw.qme.socket.SocketService;
import com.jw.qme.socket.message.ChatMessage;
import com.jw.qme.utils.MessageProtocol;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class MediaFileServiceImpl extends ServiceImpl<MediaFileMapper, MediaFile> implements MediaFileService {

    private final SocketService socketService;

    @Value("${file.upload-dir:uploads}")
    private String uploadDir;

    @Override
    public String uploadFile(MultipartFile file, String senderId, String receiverId) throws IOException {
        // 创建上传目录
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String uniqueFileName = UUID.randomUUID() + fileExtension;
        Path filePath = uploadPath.resolve(uniqueFileName);

        // 保存文件到本地
        Files.write(filePath, file.getBytes());

        // 构建媒体文件对象并保存到数据库
        MediaFile mediaFile = new MediaFile();
        mediaFile.setFileName(originalFilename);
        mediaFile.setFileType(determineFileType(fileExtension));
        mediaFile.setFileSize(file.getSize());
        mediaFile.setContentType(file.getContentType());
        mediaFile.setUploadTime(LocalDateTime.now());
        mediaFile.setUploaderId(senderId);
        mediaFile.setReceiverId(receiverId);
        mediaFile.setStatus("pending");
        mediaFile.setDownloadCount(0);
        mediaFile.setPath(filePath.toString());

        this.save(mediaFile); // 使用 MyBatis Plus 的 save 方法

        // todo 使用 socket 推送消息给接收方


        return mediaFile.getId().toString();
    }

    private String determineFileType(String extension) {
        if (extension == null) return "unknown";
        switch (extension.toLowerCase()) {
            case ".jpg":
            case ".jpeg":
            case ".png":
            case ".gif":
                return "image";
            case ".mp4":
            case ".avi":
            case ".mkv":
                return "video";
            case ".mp3":
            case ".wav":
                return "audio";
            default:
                return "other";
        }
    }

    @Override
    public byte[] downloadFile(String fileId) throws IOException {
        MediaFile mediaFile = this.getById(fileId);
        if (mediaFile == null || !Files.exists(Paths.get(mediaFile.getPath()))) {
            throw new FileNotFoundException("文件不存在");
        }

        // 更新下载次数
        mediaFile.setDownloadCount(mediaFile.getDownloadCount() + 1);
        this.updateById(mediaFile);

        return Files.readAllBytes(Paths.get(mediaFile.getPath()));
    }

    @Override
    public MediaFile getMediaFileById(String fileId) {
        return this.getById(fileId);
    }
}
